package com.s64.ch08.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.s64.ch08.entity.AjaxResult;
import com.s64.ch08.entity.User;
import com.s64.ch08.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author baomidou
 * @since 2023-11-30
 */
@RestController
@RequestMapping("/users")
@Slf4j
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PreAuthorize("hasAuthority('user:list')")
    @GetMapping
    public AjaxResult list(User user, int pageNo, int pageSize) {
        LambdaQueryWrapper<User> queryWrapper =
                Wrappers.lambdaQuery(User.class).like(StringUtils.hasText(user.getNickName()), User::getNickName, user.getNickName())
                        .eq(user.getDeptId() != null, User::getDeptId, user.getDeptId());
        Page<User> page = userService.page(Page.of(pageNo, pageSize), queryWrapper);
        return AjaxResult.ok(page);
    }

    @PreAuthorize("hasAuthority('user:list')")
    @GetMapping("/{userId}")
    public AjaxResult get(@PathVariable Long userId) {
        return AjaxResult.ok(userService.getById(userId));
    }

    @PreAuthorize("hasAuthority('user:add')")
    @PostMapping
    public AjaxResult add(@RequestBody User user) {
        rabbitTemplate.convertAndSend("fanout", null, user);
        log.info("发送用户创建消息成功");
        return AjaxResult.ok();
    }

//    @PreAuthorize("hasAuthority('user:delete')")
    @PreAuthorize("hasRole('employee')")
    @DeleteMapping("/{userId}")
    public AjaxResult del(@PathVariable Long userId) {
        return AjaxResult.ok(userService.removeById(userId));
    }

    @PreAuthorize("hasAuthority('user:update')")
    @PutMapping
    public AjaxResult update(@RequestBody User user) {
        return AjaxResult.ok(userService.updateById(user));
    }
}
